package top.lyjwn.todo.common.utils;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JWTUtil {

	// 过期时间5分钟
	private static final long EXPIRE_TIME = 60 * 60 * 1000;

	private final static Logger log = LoggerFactory.getLogger("error");
	
	/**
	 * 校验token是否正确
	 *
	 * @param token  密钥
	 * @param secret 用户的密码
	 * @return 是否正确
	 */
	public static boolean verify(String token, String redisKEY, String password) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(password);
			JWTVerifier verifier = JWT.require(algorithm).withClaim("redisKEY", redisKEY).build();
			verifier.verify(token);
			return true;
		} catch (Exception e) {
			log.info(e.getMessage());
			return false;
		}
	}

	/**
	 * 获得token中的信息无需password解密也能获得
	 *
	 * @return token中包含的用户名
	 */
	public static String getRedisKEY(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("redisKEY").asString();
		} catch (JWTDecodeException e) {
			log.info(e.getMessage());
			return null;
		}
	}

	/**
	 * 生成签名,5min后过期
	 *
	 * @param username 用户名
	 * @param secret   用户的密码
	 * @return 加密的token
	 */
	public static String sign(String redisKEY, String password) {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(password);
		// 附带username信息
		return JWT.create().withClaim("redisKEY", redisKEY).withExpiresAt(date).sign(algorithm);
	}
}
